import cropperModal from "@/components/cropper/index.vue";
import { fileBase64 } from "@/utils/util";
import { shopgoodscategorytree, addObj, putObj } from '@/api/shop/GoodsCategory.js'
import { upLoad } from '@/api/shop/upLoad.js'
import config from '@/config/appConfig'

export default {
    components: {
        cropperModal
    },
    data() {
        // var valiImg = (rule, value, callback) => { // 图片验证
        //     if (!this.hasFmt) {
        //         callback(new Error('请上传类目图标'));
        //     } else {
        //         callback();
        //     }
        // }
        return {
            dialogVisible: false,
            dialogVisibleTile: "",
            loading: false,
            labelWidth: "120px",
            rules: {
                categoryName: [
                    { required: true, message: '请输入分组名称，不超过15个字', trigger: 'blur' }
                ],
                categoryIcon: [
                    {
                        required: true, message: '请上传类目图标', trigger: 'change'
                    }
                ]

            },
            ruleForm: {},
            form: {},
            disabled: false,
            sjlmList: [],  //类目
            imageUrl: "",
            loading: false,  //上传
            optionsData: {
                title: "商品图片",     //弹框表头
                img: '',   //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 326, //默认生成截图框宽度
                autoCropHeight: 412, //默认生成截图框高度
                fixedBox: true //固定截图框大小 不允许改变
            },
            number: 0,
            fileList: [],
            fileListUrl: [], //放大展示
            businessType: '',
            imgUrlList: []
        };
    },
    methods: {
        getCategory(row) {
            this.ruleForm = {}
            this.fileList = []
            this.imgUrlList = []
            shopgoodscategorytree({ businessType: this.businessType }).then(val => {
                let data = val.data
                console.log(data)
                this.sjlmList = data.map(item => {
                    return {
                        label: item.categoryName,
                        value: item.categoryId,
                        children: item.children.map(items => {
                            return {
                                label: items.categoryName,
                                value: items.categoryId,
                            }
                        })
                    }
                })
                if (row.categoryName) {   //编辑回显
                    let obj = { ...row }
                    console.log(obj)
                    if (obj.pid == '0') {
                        obj.pid = ''
                    }
                    if (obj.categoryIcon) {   //图片回显
                        let pic = []            //图片回显
                        this.fileList = []
                        if (row.categoryIcon.indexOf(',') > -1) {
                            pic = row.categoryIcon.splice(',')
                            pic.forEach(item => {
                                this.fileList.push({ url: item, name: '类目图片' })
                                this.imgUrlList.push({ url: item, name: '类目图片' })
                            })
                        } else {
                            this.fileList.push({ url: config.url + row.categoryIcon, name: '类目图片' })
                            this.imgUrlList.push({ url: row.categoryIcon, name: '类目图片' })
                        }
                    }

                    this.ruleForm = obj
                    console.log(this.ruleForm)
                }
            })
        },
        handleClose() {
            this.dialogVisible = false
            this.ruleForm = {}
            this.fileList = []
        },
        handleSure() {
            let obj = {}
            let urlList = [...this.imgUrlList]
            if (urlList.length) {  //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(config.url) > -1) {  //截取路径
                        item.url = item.url.replace(config.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.categoryIcon = imgList.join(',')
            }
            Object.assign(obj, this.ruleForm, { businessType: this.businessType, showFlag: "01", deptId: this.$store.getters.userInfo.sysUser.deptId, tenantId: this.$store.getters.userInfo.sysUser.tenantId, })
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    addObj(obj).then(val => {
                        this.$message.success('添加成功')
                        this.$parent.$parent.getList({}, 1, this.businessType)
                        this.dialogVisible = false
                    })
                } else {
                    // this.$message.error('添加失败')
                    return false;
                }
            });
        },
        handleUpdata() {
            let obj = {}
            let urlList = [...this.imgUrlList]
            if (urlList.length) {  //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(config.url) > -1) {  //截取路径
                        item.url = item.url.replace(config.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.categoryIcon = imgList.join(',')
            }
            console.log(this.ruleForm)
            Object.assign(obj, this.ruleForm, { businessType: this.businessType, deptId: this.$store.getters.userInfo.sysUser.deptId, tenantId: this.$store.getters.userInfo.sysUser.tenantId })
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (!obj.pid) {
                        obj.pid = '0'
                        obj.showFlag = ''
                    }
                    putObj(obj).then(val => {
                        this.$message.success('编辑成功')
                        this.$parent.$parent.getList({}, 1, this.businessType)
                        this.dialogVisible = false
                    })
                } else {
                    // this.$message.error('编辑失败')
                    return false;
                }
            });
        },
        lmmcChange() {               //类目名称查重

        },
        handleChange(info) {  //上传触发
            let { options } = this;
            console.log(info)
            fileBase64(info.file.originFileObj).then(result => {
                let target = Object.assign({}, options, {
                    img: result.result,
                    files: result.files
                })
                this.$refs['cropperModal'].edit(target);
            })
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('图片格式不支持！');
            }
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error('图片大小限制在1MB内!');
            }
            return isJpgOrPng && isLt1M;
        },
        handleCropperSuccess(data) {  //图片裁切完成保存
            // fileBase64(data).then(result => {
            //     this.ruleForm.categoryIcon = result.result
            //     this.fileListUrl.push(this.ruleForm.categoryIcon)
            //     this.fileList.push({
            //         uid: this.number++,
            //         name: 'image.png',
            //         status: 'done',
            //         url: this.ruleForm.categoryIcon
            //     })
            // })
            upLoad(data).then(res => {
                console.log(res)
                this.imgUrlList.push(res.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
        },
        delUplod(file) {
            const index = this.fileList.indexOf(file)
            const newFileList = this.fileList.slice()
            newFileList.splice(index, 1)
            this.fileList = newFileList
            this.imgUrlList.splice(index, 1)
        },
    }
};